﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using MyMes.Infrastructure;
using MyMES.Dto;
using MyMES.IServices.MaterialCatalogs;
using VOL.Core.Extensions;
using VOL.Entity.DomainModels;
using VOL.Entity.DomainModels.Repository;

namespace MyMES.Services.MaterialCatalogs
{
    public class MaterialCatalogService : IMaterialCatalogService
    {
        private readonly IBaseRepository<MaterialCatalog> _materialBaseRepository;

        public MaterialCatalogService(IBaseRepository<MaterialCatalog> materialBaseRepository)
        {
            _materialBaseRepository = materialBaseRepository;
        }

        public List<MaterialCatalogTreeDto> BuildTree(List<MaterialCatalogTreeDto> nodes, int parentId = 0)
        {
            return nodes
                .Where(x => x.ParentId == parentId)
                .OrderBy(x => x.OrderById)
                .Select(x =>
                {
                    x.Children = BuildTree(nodes, x.Id);
                    return x;
                })
                .ToList();
        }
        public async Task<List<MaterialCatalogTreeDto>> GetMaterialCatalogTreeAsync()
        {
            // 查询所有数据
            var list = await _materialBaseRepository
                .GetAll()
                .OrderBy(x => x.OrderById).ToListAsync();

            // 映射为DTO
            var dtoList = list.Select(x => new MaterialCatalogTreeDto
            {
                Id = x.Id,
                ClassifyName = x.ClassifyName,
                OrderById = x.OrderById ?? 0,
                MaterialName = x.MaterialName,
                Status = x.Status ?? 0,
                CreateTime = x.CreateTime ?? DateTime.MinValue,
                ParentId = x.ParentId ?? 0
            }).ToList();

            // 组装树形结构
            return BuildTree(dtoList, 0);
        }

        /// <summary>
        /// 新增分类
        /// </summary>
        public async Task<bool> AddAsync(MaterialCatalog entity)
        {
            try
            {
                // 验证同级分类名称是否重复
                var exists = await _materialBaseRepository.GetAll()
                    .AnyAsync(x => x.ParentId == entity.ParentId &&
                                  x.ClassifyName == entity.ClassifyName);

                if (exists)
                {
                    throw new Exception("同级分类下已存在相同名称");
                }

                // 设置创建时间
                entity.CreateTime = DateTime.Now;

                // 如果未设置排序号，获取同级最大排序号+1
                if (!entity.OrderById.HasValue)
                {
                    var maxOrder = await _materialBaseRepository.GetAll()
                        .Where(x => x.ParentId == entity.ParentId)
                        .MaxAsync(x => (int?)x.OrderById) ?? 0;
                    entity.OrderById = maxOrder + 1;
                }

                // 使用 Insert 方法而不是 AddAsync
                await _materialBaseRepository.AddAsync(entity);

                return true;
            }
            catch (Exception ex)
            {
                throw new Exception($"添加分类失败：{ex.Message}");
            }
        }

        /// <summary>
        /// 修改分类
        /// </summary>
        public async Task<bool> UpdateAsync(MaterialCatalog entity)
        {
            try
            {
                // 验证同级分类名称是否重复(排除自身)
                var exists = await _materialBaseRepository.GetAll()
                    .AnyAsync(x => x.Id != entity.Id &&
                                  x.ParentId == entity.ParentId &&
                                  x.ClassifyName == entity.ClassifyName);

                if (exists)
                {
                    throw new Exception("同级分类下已存在相同名称");
                }

                var original = await _materialBaseRepository.FindAsync(entity.Id);
                if (original == null)
                {
                    throw new Exception("分类不存在");
                }

                // 更新属性
                original.ClassifyName = entity.ClassifyName;
                original.OrderById = entity.OrderById;
                original.MaterialName = entity.MaterialName;
                original.Status = entity.Status;

                // 使用 Update 方法
                await _materialBaseRepository.UpdateAsync(original);

                return true;
            }
            catch (Exception ex)
            {
                throw new Exception($"修改分类失败：{ex.Message}");
            }
        }

        /// <summary>
        /// 删除分类
        /// </summary>
        public async Task<bool> DeleteAsync(int id)
        {
            try
            {
                // 检查是否存在子分类
                var hasChildren = await _materialBaseRepository.GetAll()
                    .AnyAsync(x => x.ParentId == id);

                if (hasChildren)
                {
                    throw new Exception("该分类下还有子分类，无法删除");
                }

                var entity = await _materialBaseRepository.FindAsync(id);
                if (entity == null)
                {
                    throw new Exception("分类不存在");
                }

                // 使用 Delete 方法
                await _materialBaseRepository.Remove(entity);

                return true;
            }
            catch (Exception ex)
            {
                throw new Exception($"删除分类失败：{ex.Message}");
            }
        }

    }
}
